import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt

# load template and searched image
imgForSearch = cv.imread('../data/messi5.jpg', 0)
imgTemplate = cv.imread('../data/messi_face.jpg', 0)
# save for drawing matched rect
w, h = imgTemplate.shape[::-1]

# All the 6 methods for comparison in a list
methods = ['cv.TM_CCOEFF', 'cv.TM_CCOEFF_NORMED',
           'cv.TM_CCORR', 'cv.TM_CCORR_NORMED',
           'cv.TM_SQDIFF', 'cv.TM_SQDIFF_NORMED']

for meth in methods:
    # we need keep org img to be searched every loop so
    # we should draw sth on a new img in case that org img is changed
    imgForDraw = imgForSearch.copy()

    # change string to int via python function eval
    method = eval(meth)
    print(type(meth), type(method))

    # Apply template Matching
    res = cv.matchTemplate(imgForSearch, imgTemplate, method)

    min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)
    # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
    if method in [cv.TM_SQDIFF, cv.TM_SQDIFF_NORMED]:
        top_left = min_loc
    else:
        top_left = max_loc

    # draw and visualize
    bottom_right = (top_left[0] + w, top_left[1] + h)
    cv.rectangle(imgForDraw, top_left, bottom_right, 255, 2)
    cv.normalize(res, res, 0, 1, cv.NORM_MINMAX, -1)
    #     print(res)
    #     break

    cv.imshow("imgTemplate", imgTemplate)
    cv.imshow("imgOrg", imgForSearch)
    cv.imshow("matchRes", res)
    cv.imshow("imgForDraw", imgForDraw)
    cv.waitKey(0)

cv.destroyAllWindows()